package com.aier.user.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import com.aier.common.dao.ICommonDAO;
import com.aier.user.entity.Follow;
import com.aier.user.entity.Fresh;
import com.aier.user.entity.FreshComment;
import com.aier.user.entity.FreshFavorite;
import com.aier.user.entity.FreshPraise;
import com.aier.user.entity.User;
import com.aier.user.entity.mapper.FollowRowMapper;
import com.aier.user.entity.mapper.FreshCommentRowMapper;
import com.aier.user.entity.mapper.FreshFavoriteRowMapper;
import com.aier.user.entity.mapper.FreshPraiseRowMapper;
import com.aier.user.entity.mapper.FreshRowMapper;
import com.aier.user.entity.mapper.UserRowMapper;
import com.aier.user.service.IHomeForumsService;

@Component("homeForumsService")
public class HomeForumsServiceImpl_J implements IHomeForumsService {

    @Resource(name = "commonDao")
    private ICommonDAO commonDao;

    public void setCommonDao(ICommonDAO commonDao) {
        this.commonDao = commonDao;
    }

    @Override
    public int insertFresh(Long uid, String content, String img, String special,Short power,Long fgid) {
        // 保存新鲜事
        Fresh fresh = new Fresh();
        fresh.setUid(uid);
        fresh.setContent(content);
        fresh.setImg(img);
        fresh.setType((short)0);
        fresh.setCdate(new Timestamp(new Date().getTime()));
        fresh.setPower(power);
        fresh.setFgid(fgid);
        KeyHolder kh = commonDao.insert(FreshRowMapper.getPreparedStatementCreator(fresh),new GeneratedKeyHolder());
        
        // 如果有@保存,否则返回
//        if (null == special || "".equals(special)) {
//            return 1;
//        }
//        for (int i=0;i<special.split(",").length;i++) {
//            commonDao.update("insert into special(uid,suid,type,relativeid,cdate) values (?,?,?,?,?)",
//                    new Object[] {uid,special.split(",")[i],1,kh.getKey().longValue(),new Timestamp(new Date().getTime())});
//        }
        List<String> list = searchSpecial(content);
        for (String str : list) {
            User user = (User) commonDao.listByObject("select * from user where nickname = ?", new Object[]{str},new UserRowMapper());
            if (user != null) {
                commonDao.update("insert into special(uid,suid,type,relativeid,cdate) values (?,?,?,?,?)",
                        new Object[] {uid,user.getUid(),1,kh.getKey().longValue(),new Timestamp(new Date().getTime())});
            }
        }
        
        return 1;
    }
    

    @Override
    public int insertOtherFresh(Long uid, String content, String special,
            Short power, Long fgid, Long fid,int cflag) {
        
        Fresh fr = (Fresh) commonDao.listByObject("select *,UNIX_TIMESTAMP(cdate)*1000 as stamp from fresh where fid = ?", 
                new Object[]{fid},new FreshRowMapper());
        Long relativeid = fid;
        // 将原创新鲜事的转发次数+1
        commonDao.update("update fresh set tcount = IFNULL(tcount,0)+1  where fid = ?",new Object[] {relativeid});
        if (fr.getType() == 1) {
            relativeid = fr.getRelativeid();
            // 将原创新鲜事的转发次数+1
            commonDao.update("update fresh set tcount = IFNULL(tcount,0)+1  where fid = ?",new Object[] {relativeid});
        }
        // 保存新鲜事
        Fresh fresh = new Fresh();
        fresh.setUid(uid);
        fresh.setContent(content);
        fresh.setType((short)1);
        fresh.setCdate(new Timestamp(new Date().getTime()));
        fresh.setPower(power);
        fresh.setFgid(fgid);
        fresh.setRelativeid(relativeid);
        KeyHolder kh = commonDao.insert(FreshRowMapper.getPreparedStatementCreator(fresh),new GeneratedKeyHolder());
        
        // 如果有@保存,否则返回
//        if (null != special && !"".equals(special)) {
//            
//            for (int i=0;i<special.split(",").length;i++) {
//                commonDao.update("insert into special(uid,suid,type,relativeid,cdate) values (?,?,?,?,?)",
//                        new Object[] {uid,special.split(",")[i],1,kh.getKey().longValue(),new Timestamp(new Date().getTime())});
//            }
//        }
        List<String> list = searchSpecial(content);
        for (String str : list) {
            User user = (User) commonDao.listByObject("select * from user where nickname = ?", new Object[]{str},new UserRowMapper());
            if (user != null) {
                commonDao.update("insert into special(uid,suid,type,relativeid,cdate) values (?,?,?,?,?)",
                        new Object[] {uid,user.getUid(),1,kh.getKey().longValue(),new Timestamp(new Date().getTime())});
            }
        }
        
        // 是否同时评论原作者
        if (cflag == 1) {
            Fresh f = (Fresh) commonDao.listByObject("select *,UNIX_TIMESTAMP(cdate)*1000 as stamp from fresh where fid = ?", 
                    new Object[]{fid},new FreshRowMapper());
            insertFreshComment(uid,fid,f.getUid(),content,f.getContent(),(short)1,0,0,null);
        }
        
        return 1;
    }

    @Override
    public int insertFreshComment(Long uid,Long fid,Long rfcuid,String content,String rcontent,Short ctype,int flag,int cflag,String special) {
        // 新增评论
        FreshComment fc = new FreshComment();
        fc.setFcuid(uid);
        fc.setFid(fid);
        fc.setRfcuid(rfcuid);
        fc.setContent(content);
        fc.setRcontent(rcontent);
        fc.setType(ctype);
        fc.setCdate(new Timestamp(new Date().getTime()));
        KeyHolder kh = commonDao.insert(FreshCommentRowMapper.getPreparedStatementCreator(fc),new GeneratedKeyHolder());
        
        // 修改新鲜事的评论次数
        commonDao.update("update fresh set ccount = IFNULL(ccount,0)+1  where fid = ?",new Object[] {fid});
        
        // 转发
        if (flag ==1) {
            insertOtherFresh(uid, content, "", (short)0, null, fid, 0);
        }
        // 是否评论给原作者
        if (cflag == 1) {
            Fresh fr = (Fresh) commonDao.listByObject("select *,UNIX_TIMESTAMP(cdate)*1000 as stamp from fresh where fid = ?", 
                    new Object[]{fid},new FreshRowMapper());
            Long ruid = ((Fresh)commonDao.listByObject("select *,UNIX_TIMESTAMP(cdate)*1000 as stamp from fresh where fid = ?", 
                    new Object[]{fr.getRelativeid()},new FreshRowMapper())).getUid();
            
            commonDao.update("insert into fresh_comment(fcuid,fid,rfcuid,content,rcontent,type,cdate) values(?,?,?,?,?,?,?)",
                    new Object[]{uid,fr.getRelativeid(),ruid,content,fr.getContent(),1,new Timestamp(new Date().getTime())});
            commonDao.update("update fresh set ccount = IFNULL(ccount,0)+1  where fid = ?",new Object[] {fr.getRelativeid()});
        }
        // 如果有@保存,否则返回
//        if (null == special || "".equals(special)) {
//            return 1;
//        }
//        for (int i=0;i<special.split(",").length;i++) {
//            commonDao.update("insert into special(uid,suid,type,relativeid,cdate) values (?,?,?,?,?)",
//                    new Object[] {uid,special.split(",")[i],2,kh.getKey().longValue(),new Timestamp(new Date().getTime())});
//        }
        List<String> list = searchSpecial(content);
        for (String str : list) {
            User user = (User) commonDao.listByObject("select * from user where nickname = ?", new Object[]{str},new UserRowMapper());
            if (user != null) {
                commonDao.update("insert into special(uid,suid,type,relativeid,cdate) values (?,?,?,?,?)",
                        new Object[] {uid,user.getUid(),1,kh.getKey().longValue(),new Timestamp(new Date().getTime())});
            }
        }
        return 1;
    }

    @Override
    public int updateFreshBcount(Long fid) {
        // 修改新鲜事的浏览次数
        commonDao.update("update fresh set bcount = IFNULL(bcount,0)+1  where fid = ?",new Object[] {fid});
        return 1;
    }

    @Override
    public int updateFreshPraise(Long uid,Long fid, int ptype) {
        List<?> obj = commonDao.list("select * from fresh_praise where uid =? and fid=?",new Object[]{uid,fid});
        if (ptype == 0) {
            // 新增赞的记录
            if (obj == null || obj.size() == 0) {
                commonDao.update("insert into fresh_praise(uid,fid,cdate) values (?,?,?)",
                        new Object[] {uid,fid,new Timestamp(new Date().getTime())});
                // 修改新鲜事的赞的次数
                commonDao.update("update fresh set pcount = IFNULL(pcount,0)+1  where fid = ?",new Object[] {fid});
            }
            
        } else {
            // 删除赞的记录
            if (obj != null && obj.size() > 0) {
                commonDao.update("delete from fresh_praise where uid=? and fid=?",
                        new Object[] {uid,fid});
                commonDao.update("update fresh set pcount = IFNULL(pcount,0)-1  where fid = ?",new Object[] {fid});
            }
        }
        
        return 1;
    }

    @Override
    public int insertFavoriteFresh(Long uid, Long fid) {
        // 新增收藏
        if (commonDao.list("select * from fresh_favorite where fuid =? and fid=?",new Object[]{uid,fid}).size()==0) {
            commonDao.update("insert into fresh_favorite(fuid,fid,cdate) values (?,?,?)",
                    new Object[] {uid,fid,new Timestamp(new Date().getTime())});
        }
        return 1;
    }

    @Override
    public int deleteFavoriteFresh(Long ffid) {
        // 取消收藏
        commonDao.update("delete from fresh_favorite where ffid=?",
                new Object[] {ffid});
        return 1;
    }
    
    @Override
    public int deleteFFByUid(Long uid, Long fid) {
        // 取消收藏
        commonDao.update("delete from fresh_favorite where fuid=? and fid=?",
                new Object[] {uid,fid});
        return 1;
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Follow> searchAllFollow(Long uid) {
        return (List<Follow>) commonDao.list("SELECT fl.fuid AS fuid, fl.remark, u.nickname, " +
        		"(SELECT COUNT(*) FROM special s WHERE s.uid = ? AND s.suid = fl.fuid ) AS count FROM follow fl " +
        		"LEFT JOIN `user` u ON u.uid = fl.fuid WHERE fl.uid = ? ORDER BY count DESC",
        		new Object[]{uid,uid},new FollowRowMapper());
    }

    @Override
    public Map<String, Object> searchAllFresh(int page, int pagesize, Long uid) {
        String sql = "select f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp, u.nickname, u.headimg as headimg from fresh f left join `user` u " +
        		"on u.uid = f.uid where f.uid = ? or ( f.power = 0 and f.uid in ( select fo.fuid from follow fo where fo.uid = ? )) " +
        		"or ( f.power = 1 and f.uid in ( select fr.auid from friend fr where fr.uid = ? )) or " +
        		"( f.power = 3 and f.uid in ( select fo.fuid from follow fo where fo.uid = ? AND fo.fgid = f.fgid )) order by f.cdate desc";
        
        return commonDao.queryPage(sql,page, pagesize, new Object[] {uid,uid,uid,uid},new FreshRowMapper());
    }

    @Override
    public Fresh searchFresh(Long fid,int type) {
        if (type == 1) {
            return (Fresh) commonDao.listByObject(
                    "select f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp, u.nickname, u.headimg as headimg from fresh f left join `user` u " +
                    "on u.uid = f.uid where f.fid = ?", 
                    new Object[]{fid}, new FreshRowMapper());
        } else {
            return (Fresh) commonDao.listByObject(
                    "select f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp, u.nickname, u.headimg as headimg from fresh f left join `user` u " +
                    "on u.uid = f.uid left join fresh_comment fc on fc.fid = f.fid where fc.fcid = ?", 
                    new Object[]{fid}, new FreshRowMapper());
        } 
        
    }

    @Override
    public Map<String, Object> searchFriendFresh(int page, int pagesize,
            Long uid) {
        String sql = "select f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp, u.nickname, u.headimg as headimg from fresh f left join `user` u " +
        		"on u.uid = f.uid where (f.power = 1 and f.uid in (select fr.auid from friend fr where fr.uid = ? )) " +
        		"or ( f.power = 0 and f.uid in ( select fr.auid from friend fr where fr.uid = ? )) order by f.cdate desc";
        
        return commonDao.queryPage(sql,page, pagesize, new Object[] {uid,uid},new FreshRowMapper());
    }

    @Override
    public Map<String, Object> searchFavorite(int page,int pagesize,Long uid) {
        String sql = "select ff.ffid,ff.fuid,f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp,u.nickname, u.headimg from fresh_favorite ff " +
        		"left join fresh f on f.fid = ff.fid left join `user` u on u.uid = f.uid where ff.fuid = ? order by ff.cdate desc";
        return commonDao.queryPage(sql,page, pagesize, new Object[] {uid},new FreshFavoriteRowMapper());
    }

    @Override
    public Map<String, Object> searchCommentByFid(int page,int pagesize,Long fid) {
        return commonDao.queryPage("select fc.*, u.nickname, u.headimg from fresh_comment fc left join `user` u " +
        		"on u.uid = fc.fcuid where fc.fid = ? order by fc.cdate desc", 
                page, pagesize, new Object[]{fid}, new FreshCommentRowMapper());
    }

    @Override
    public Map<String, Object> searchReceiveComment(int page, int pagesize,
            Long uid) {
        return commonDao.queryPage("select fc.*, u.nickname, u.headimg from fresh_comment fc left join fresh f " +
        		"on f.fid = fc.fid left join user u on u.uid = fc.fcuid where f.uid = ? and fc.fcuid != ? order by fc.cdate desc", 
                page, pagesize, new Object[]{uid,uid}, new FreshCommentRowMapper());
    }

    @Override
    public Map<String, Object> searchSendComment(int page, int pagesize,
            Long uid) {
        String sql = "select fc.*, u.nickname, u.headimg from fresh_comment fc left join fresh f " +
        		"on f.fid = fc.fid left join user u on u.uid = f.uid where fc.fcuid = ? order by fc.cdate desc";
        
        return commonDao.queryPage(sql, 
                page, pagesize, new Object[]{uid}, new FreshCommentRowMapper());
    }

    @Override
    public FreshComment searchFreshCommentByFcid(Long fcid) {
        return (FreshComment) commonDao.listByObject("select fc.*,u.nickname,u.headimg from fresh_comment fc left join user u on u.uid = fc.fcuid " +
        		"where fc.fcid = ?", 
                new Object[]{fcid},new FreshCommentRowMapper());
    }

    @Override
    public Map<String, Object> searchPraiseAllFresh(int page, int pagesize,
            Long uid) {
        return commonDao.queryPage(
                "select fp.*,u.nickname,u.headimg from fresh_praise fp left join user u on u.uid = fp.uid left join fresh f on f.fid = fp.fid " +
                "where fp.uid != ? and f.uid = ? order by cdate", 
                page, pagesize, new Object[]{uid,uid}, new FreshPraiseRowMapper());
    }

    @Override
    public int deleteComment(Long fcid) {
            // 删除评论
        return commonDao.update("delete from fresh_comment where fcid = ?",new Object[]{fcid});
        
    }

    @Override
    public Map<String, Object> searchSpecialFresh(int page, int pagesize,
            Long uid) {
        return commonDao.queryPage("select f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp,u.nickname, u.headimg as headimg from fresh f " +
        		"left join special s on s.relativeid = f.fid left join user u on u.uid = f.uid where s.suid = ? and s.type = 1 " +
        		"order by s.cdate desc",
                page, pagesize, new Object[]{uid}, new FreshRowMapper());
    }
    
    @Override
    public Map<String, Object> searchSpecialComment(int page, int pagesize,
            Long uid) {
        String sql = "select fc.*,u.nickname,u.headimg,(select nickname from user where uid = fc.rfcuid) as rnickname from fresh_comment fc " +
        		"left join user u on u.uid = fc.fcuid left join special s on s.relativeid = fc.fcid where s.suid = ? and s.type = 2 " +
        		"order by s.cdate desc";
        return commonDao.queryPage(sql, 
                page, pagesize, new Object[]{uid}, new FreshCommentRowMapper());
    }

    @Override
    public Map<String, Object> searchFollowDo(int page,int pagesize,Long uid) {
        return commonDao.queryPage("select f.*,u.nickname,u.headimg,us.nickname as fnickname,us.headimg as fheadimg from follow f left join user u " +
        		"on u.uid = f.uid left join user us on us.uid = f.fuid where f.uid in (select fuid from follow where uid = ?) and " +
        		"f.uid not in (select auid from friend where uid = ?) and f.fuid !=? order by cdate desc",
        		page,pagesize,new Object[]{uid,uid,uid}, new FollowRowMapper(FollowRowMapper.FOLLOW_DO));
    }

    @Override
    public Map<String, Object> searchFriendDo(int page,int pagesize,Long uid) {
        String sql = "select f.frid as foid, f.uid, f.auid as fuid, f.remark, f.state, f.cdate, u.nickname, u.headimg, us.nickname as fnickname, " +
        		"us.headimg as fheadimg from friend f left join user u on u.uid = f.uid left join user us on us.uid = f.auid " +
        		"where f.uid in ( select auid from friend where uid = ? ) and f.state = 1 and f.auid != ? order by cdate desc";
        return commonDao.queryPage(sql,
                page,pagesize,new Object[]{uid,uid}, new FollowRowMapper(FollowRowMapper.FOLLOW_DO));
    }

    @Override
    public FreshPraise searchPraiseByCon(Long uid, Long fid) {
        return (FreshPraise) commonDao.listByObject("select * from fresh_praise where uid = ? and fid = ?", 
                new Object[]{uid,fid},new FreshPraiseRowMapper());
    }

    @Override
    public FreshFavorite searchFavoriteByCon(Long uid, Long fid) {
        return (FreshFavorite)commonDao.listByObject("select * from fresh_favorite where fuid = ? and fid = ?", 
                    new Object[]{uid,fid},new FreshFavoriteRowMapper(FreshFavoriteRowMapper.FAVORITE_BRIEF));
        
    }

    @Override
    public int deleteFresh(Long fid) {
        return commonDao.update("delete from fresh where fid = ?",new Object[]{fid});
    }

    @Override
    public Map<String, Object> searchFreshSelf(int page, int pagesize, Long uid) {
        String sql = "select f.*,UNIX_TIMESTAMP(f.cdate)*1000 as stamp, u.nickname, u.headimg as headimg from fresh f left join `user` u " +
        		"on u.uid = f.uid where f.uid = ? order by f.cdate desc";
        
        return commonDao.queryPage(sql,page, pagesize, new Object[] {uid},new FreshRowMapper());
    }
    
    private List<String> searchSpecial(String content) {
        List<String> list = new ArrayList<String>();
        String reg = "[^\u4e00-\u9fa5^_^\\-^a-z^A-Z^0-9]";
        Pattern patt = Pattern.compile(reg);  
        for (int i=0;i<content.length();i++) {
            if (content.charAt(i) == '@') {
                String str = content.substring(i+1);
                for (int j= 0;j<str.length();j++) {
                    if(patt.matcher(str.charAt(j)+"").matches()){
                        if (str.substring(0, j).length() > 0) {
                            list.add(str.substring(0, j));
                        }
                        break;
                    }
                }
            }
        }
        
        HashSet<String> h = new HashSet<String>(list);
        list.clear();
        list.addAll(h);
        
        return list;
    }

}
